package org.biogroovy.net

/**
 * This class represents a template for a URL in the form "http://www.whatever.com?paramName=${paramName}".  The parameter placeholders in the URL can be bound.
 * @author markfortner
 *
 */
class URLTemplate {

	String template = null;

	public URLTemplate(String template){
		this.template = template;
	}

	/**
	 * This method binds the parameters in the map with a clone of the original URL template.
	 * @param params a map of parameters and values
	 * @return  a valid URL
	 */
	public String bind(Map<String, String> params){
		String clone = this.template.clone();
		params.each{key, value ->
			clone = clone.replaceAll("${" + key + "}", value);
		}
		return clone;
	}

	/**
	 * This method binds the parameters to a URL, and opens an input stream.
	 * @param params  a map of parameter names and values
	 * @return
	 * @throws IOException if there is a problem creating the URL or opening the stream.
	 */
	public InputStream getInputStream(Map<String, String> params) throws IOException{
		URL url = new URL(bind(params));
		return url.openStream();
	}
}
